package com.shenmazong.user.service.impl;

import com.alibaba.fastjson2.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.shenmazong.state.MessageTypeEnum;
import com.shenmazong.user.pojo.TbAdmin;
import com.shenmazong.user.service.TbAdminService;
import com.shenmazong.user.mapper.TbAdminMapper;
import com.shenmazong.utils.IdWorker;
import com.shenmazong.utils.ResultResponse;
import com.shenmazong.utils.TokenUtils;
import com.shenmazong.vo.*;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.crypto.bcrypt.BCrypt;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;

/**
 *
 */
@Service
public class TbAdminServiceImpl extends ServiceImpl<TbAdminMapper, TbAdmin>
    implements TbAdminService{

    @Autowired
    TbAdminMapper tbAdminMapper;

    @Autowired
    RedisTemplate redisTemplate;

    @Autowired
    RabbitTemplate rabbitTemplate;

    @Override
    public ResultResponse add(TbAdmin tbAdmin) {
        //--1 检查是否存在同名用户
        TbAdmin one = tbAdminMapper.selectOne(
                new QueryWrapper<TbAdmin>().lambda().eq(TbAdmin::getAdminName, tbAdmin.getAdminName()).last("limit 1")
        );
        if(one != null) {
            return ResultResponse.FAILED(505, "用户已经存在");
        }

        //--2 添加
        String hashpw = BCrypt.hashpw(tbAdmin.getAdminPass(), BCrypt.gensalt());
        tbAdmin.setAdminPass(hashpw);
        tbAdminMapper.insert(tbAdmin);

        //--3 返回成功
        return ResultResponse.SUCCESS();
    }

    @Override
    public ResultResponse del(IdVo idVo) {
        //--1 检查是否存在
        TbAdmin tbAdmin = tbAdminMapper.selectById(idVo.getId());
        if(tbAdmin == null) {
            return ResultResponse.FAILED(404, "用户不存在");
        }

        //--2 删除
        tbAdminMapper.deleteById(idVo.getId());

        //--3 返回成功
        return ResultResponse.SUCCESS();
    }

    @Override
    public ResultResponse set(TbAdmin tbAdmin) {
        //--1 检查是否存在
        TbAdmin one = tbAdminMapper.selectById(tbAdmin.getAdminId());
        if(one == null) {
            return ResultResponse.FAILED(404, "用户不存在");
        }

        //--2 进行修改
        tbAdmin.setAdminPass(null);
        tbAdmin.setAdminName(null);
        one.setUpdateTime(null);

        tbAdminMapper.updateById(tbAdmin);

        return ResultResponse.SUCCESS();
    }

    @Override
    public ResultResponse get(IdVo idVo) {
        //--1 检查是否存在
        TbAdmin one = tbAdminMapper.selectById(idVo.getId());
        if(one == null) {
            return ResultResponse.FAILED(404, "用户不存在");
        }

        //--2 脱密、脱敏
        one.setAdminPass(null);

        return ResultResponse.SUCCESS(one);
    }

    @Override
    public ResultResponse ListByPage(PageVo pageVo) {

        Page<TbAdmin> page = new Page<>(pageVo.getPageNum(), pageVo.getPageSize());

        QueryWrapper<TbAdmin> wrapper = new QueryWrapper<>();
        wrapper.lambda().orderByDesc(TbAdmin::getAdminId);

        Page<TbAdmin> tbAdminPage = tbAdminMapper.selectPage(page, wrapper);

        return ResultResponse.SUCCESS(tbAdminPage);
    }

    @Override
    public ResultResponse changePassword(ChangePasswordVo changePasswordVo) {
        //--1 检查是否存在
        TbAdmin one = tbAdminMapper.selectById(changePasswordVo.getUserId());
        if(one == null) {
            return ResultResponse.FAILED(404, "用户不存在");
        }

        //--2 设置密码并修改数据库
        boolean checkpw = BCrypt.checkpw(changePasswordVo.getOldPass(), one.getAdminPass());
        if(!checkpw) {
            return ResultResponse.FAILED(401, "密码不正确");
        }

        String hashpw = BCrypt.hashpw(changePasswordVo.getNewPass(), BCrypt.gensalt());
        one.setAdminPass(hashpw);
        one.setUpdateTime(null);
        tbAdminMapper.updateById(one);

        return ResultResponse.SUCCESS();
    }

    @Override
    public ResultResponse login(LoginVo loginVo) {
        //--1 检查是否存在
        TbAdmin one = tbAdminMapper.selectOne(
                new QueryWrapper<TbAdmin>().lambda().eq(TbAdmin::getAdminName, loginVo.getUserName()).last("limit 1")
        );
        if(one == null) {
            return ResultResponse.FAILED(404, "用户不存在");
        }

        //--2 校验密码
        boolean checkpw = BCrypt.checkpw(loginVo.getUserPass(), one.getAdminPass());
        if(!checkpw) {
            return ResultResponse.FAILED(403, "用户密码不正确");
        }

        //--3 生成token
        String token = TokenUtils.token()
                .setKey("123456")
                .setExpire(60 * 30)
//                .createToken("userId", "" + one.getAdminId(), "userName", one.getAdminName(), "role", "" + one.getAdminRole());
                .setClaim("userId", "" + one.getAdminId())
                .setClaim("userName", one.getAdminName())
                .setClaim("role", "" + one.getAdminRole())
                .makeToken();
        redisTemplate.opsForValue().set(token, token, 30, TimeUnit.MINUTES);

        //--4 返回用户信息
        one.setToken(token);

        //--5 脱密
        one.setAdminPass(null);

        //--6 发送消息，记录登录的日志
        PublicMessageVo messageVo = new PublicMessageVo();
        messageVo.setId(IdWorker.getId());
        messageVo.setType(MessageTypeEnum.MSG_LOGIN.getCode());
        // fastjson/jackson/gson
//        ObjectMapper objectMapper = new ObjectMapper();
//        String message = objectMapper.writeValueAsString(one);
        String data = JSON.toJSONString(one);
        messageVo.setMessage(data);

        String message = JSON.toJSONString(messageVo);

        rabbitTemplate.convertAndSend("public_message_exchange", "msg.login", message);


        return ResultResponse.SUCCESS(one);
    }


}




